package com.example.spring.boot.spring.exception;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


public class HandlerExceptionResolverImpl implements HandlerExceptionResolver {


    //@Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    public RequestMappingHandlerAdapter getHandlerAdapter() {
        return handlerAdapter;
    }
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        List<HandlerMethodReturnValueHandler> returnValueHandlerList =  handlerAdapter.getReturnValueHandlers();
        RequestResponseBodyMethodProcessor processor = null;
        for (HandlerMethodReturnValueHandler returnValueHandler : returnValueHandlerList) {
            if (returnValueHandler instanceof  RequestResponseBodyMethodProcessor) {
                processor= (RequestResponseBodyMethodProcessor)returnValueHandler;
            }
        }
        ServletWebRequest webRequest = new ServletWebRequest(request, response);
        try {
            response.setStatus(HttpStatus.OK.value());
            webRequest.getResponse().setContentType(MediaType.APPLICATION_JSON.toString());
            processor.handleReturnValue(ex, handlerMethod.getReturnType(), new ModelAndViewContainer(), webRequest);
        }catch (Exception e){

        }
        return new ModelAndView();
    }
}
